<?php

/**
 * draw db grid
 *
 * @author fsqijy
 */
require_once   BaseUtil::getModulePath("dbgrid")  .  '/DBGridFilter.php';
require_once   BaseUtil::getModulePath("dbgrid")  .  '/DBGridConstant.php';
require_once   BaseUtil::getModulePath("dbgrid")  .  '/BaseDBGridDraw.php';
class DBGridDraw extends BaseDBGridDraw {

    public function  __construct($view) {
        parent::__construct($view);
    }

    public function render(){
         $html = "<form id='dbgridForm' method='post' action='".$this->_filterAction."'>";
         $filter = $this->renderForm();
         $grid = $this->renderGrid();
         $html .=  $filter . $grid;
         $html .= "</form>";
         return $html;
    }

    public function renderByAjax(){
        return $this->renderGrid(true);
    }

    /**
     * for ajax
     */
    public function renderAjaxDbGrid(){
         $useAjax = isset($this->_post['useAjax']) ? $this->_post['useAjax'] : "0";
         if($useAjax == 1){
             $html = $this->ajaxGrid($useAjax);
         }else{
             $html = "<form id='dbgridForm' method='post' action='".$this->_filterAction."'>";
             $filter = $this->renderAjaxForm();
             $grid = $this->ajaxGrid($useAjax);
             $html .=  $filter . $grid;
             $html .= "</form>";
         }
         return $html;
    }

    protected function renderForm(){
         $filter = "";
         $filter .= "<div class='dbgrid_form'>";
         $filter .= $this->dbFilter->render($this->_filters,$this->_advanceFilters,$this->_selectOptionFilter,$this->_module,$this->_post);
         $filter .= "</div>";
         $filter .= "<div class='clear'></div>";
         return $filter;
    }
    
    /**
     * for ajax
     */
    protected function renderAjaxForm(){
         $filter = "";
         $filter .= "<div class='dbgrid_form'>";
         $filter .= $this->dbFilter->render($this->_filters,$this->_advanceFilters,$this->_selectOptionFilter,$this->_module,$this->_post,true);
         $filter .= "</div>";
         $filter .= "<div class='clear'></div>";
         return $filter;
    }

    protected function renderGrid($isAjax=false){
         $html = "";
         $gridHtml = "";
         $paginationBar = "";
         //generate sql;
         $select = $this->translateDbSelect();
         //paginator setting
         $currentPageNumber = isset($this->_post['currentPageNumber']) ? $this->_post['currentPageNumber'] : 1 ;//get current page number
         $this->paginator = new Zend_Paginator(new Zend_Paginator_Adapter_DbSelect($select));
         $this->paginator->setPageRange(DBGridConstant::PAGE_RANGE);
         $this->paginator->setItemCountPerPage(isset($this->_post['dbgridPageOption']) ? intval($this->_post['dbgridPageOption']) : DBGridConstant::DEFAULT_ITEM_COUNT_PER_PAGE);
         $this->paginator->setCurrentPageNumber($currentPageNumber);
         //generate grid
         $gridHtml = $this->renderGridItems();
         //generate bar
         if($isAjax){
             $html .= $this->renderPaginationControl($this->paginator->getPages(),1);
             $html .= $gridHtml;
             $html .= $this->renderPaginationControl($this->paginator->getPages());
         }else{
             $html .= "<div class='dbgrid_centerbig' id='dbgrid_centerbig'>";
             $html .= $this->renderPaginationControl($this->paginator->getPages(),1);
             $html .= $gridHtml;
             $html .= $this->renderPaginationControl($this->paginator->getPages());
             $html .= "</div>";
         }
         return $html;
    }

    /**
     * for ajax
     */
    protected function ajaxGrid($useAjax){
         $html = "";
         $gridHtml = "";
         $paginationBar = "";
         //generate sql;
         $select = $this->translateDbSelect();
         //paginator setting
         $currentPageNumber = isset($this->_post['currentPageNumber']) ? $this->_post['currentPageNumber'] : 1 ;//get current page number
         $this->paginator = new Zend_Paginator(new Zend_Paginator_Adapter_DbSelect($select));
         $this->paginator->setPageRange(DBGridConstant::PAGE_RANGE);
         $this->paginator->setItemCountPerPage(isset($this->_post['dbgridPageOption']) ? intval($this->_post['dbgridPageOption']) : DBGridConstant::DEFAULT_ITEM_COUNT_PER_PAGE);
         $this->paginator->setCurrentPageNumber($currentPageNumber);
         //generate grid
         $gridHtml = $this->renderAjaxGridItems();
         //generate bar
         if($useAjax == 1){
             $html .= $this->renderAjaxPaginationControl($this->paginator->getPages(),1);
             $html .= $gridHtml;
             $html .= $this->renderAjaxPaginationControl($this->paginator->getPages());
         }else{
             $html .= "<div class='dbgrid_centerbig' id='dbgrid_centerbig'>";
             $html .= $this->renderAjaxPaginationControl($this->paginator->getPages(),1);
             $html .= $gridHtml;
             $html .= $this->renderAjaxPaginationControl($this->paginator->getPages());
             $html .= "</div>";
         }
         return $html;
    }

     /**
      * render grid items
      */
    protected function renderGridItems(){
         $items = $this->paginator;
         $grid = "<div class='dbgrid_center_right'>";
         $grid .= "<table cellpadding='0' cellspacing='0'>";
         $grid .= $this->renderTableThead();
         if(isset($items) && count($items) && !empty($this->_columns)){
             //if($this->_gridStyle == "search"){
                //$grid .= $this->renderSearchTableRows();
             //}else if($this->_gridStyle == "simple"){
                $grid .= $this->renderTableRows();
             //}
         }
         $grid .= "</table>";
         $grid .= "</div>";
         return $grid;
    }

    /**
     * for ajax
     */
    protected function renderAjaxGridItems(){
         $items = $this->paginator;
         $grid = "<div class='dbgrid_center_right'>";
         $grid .= "<table cellpadding='0' cellspacing='0'>";
         $grid .= $this->renderAjaxTableThead();
         if(isset($items) && count($items) && !empty($this->_columns)){
                $grid .= $this->renderAjaxTableRows();
         }
         $grid .= "</table>";
         $grid .= "</div>";
         return $grid;
    }
    
    /**
     * render grid header
     */
    protected function renderTableThead(){
        $sortOrder = isset($this->_post['sortOrder']) ? $this->_post['sortOrder'] : "";
        $sortCol = isset($this->_post['sortCol']) ? $this->_post['sortCol'] : "";
        $thead = "";
        if(!empty($this->_columns)){
             $thead .= "<thead><tr>";
             $thead .= "<td class='dbgrid_th_ckb'><input type='checkbox' onclick='javascript:DBGrid.checkAll();' id='dbgrid_all_ckb' /></td>";
             foreach($this->_columns as $col){
                 if(!empty($sortCol) && $sortCol == $col['sort']){
                     $sortOrder = strtoupper($sortOrder) == "ASC" ? "DESC" : "ASC" ;
                     $thead .= "<td class='dbgrid_th' onclick='javascript:DBGrid.clickCol(\"". $col['sort'] ."\",\"" . $sortOrder ."\");'>";
                 }else{
                     $thead .= "<td class='dbgrid_th' onclick='javascript:DBGrid.clickCol(\"". $col['sort'] ."\",\"ASC\");'>";
                 }               
                 $thead .= "<span>" . $this->escape($col['label']) . "</span>" ;
                 $thead .= "</td>";
             }
             $thead .= "</tr></thead>";
        }
        return $thead;
    }

    /**
     * for ajax
     */
    protected function renderAjaxTableThead(){
        $sortOrder = isset($this->_post['sortOrder']) ? $this->_post['sortOrder'] : "";
        $sortCol = isset($this->_post['sortCol']) ? $this->_post['sortCol'] : "";
        $thead = "";
        if(!empty($this->_columns)){
             $thead .= "<thead><tr>";
             if($this->_returnData){
                $thead .= "<td class='dbgrid_th_ckb'><input type='checkbox' onclick='javascript:DBGrid.checkAll();' id='dbgrid_all_ckb' /></td>";
             }
             foreach($this->_columns as $col){
                 $visable = $col['visable'];
                 if($visable){
                     if(!empty($sortCol) && $sortCol == $col['sort']){
                         $sortOrder = strtoupper($sortOrder) == "ASC" ? "DESC" : "ASC" ;
                         $thead .= "<td class='dbgrid_th' onclick='javascript:DBGrid.clickAjaxCol(\"". $col['sort'] ."\",\"" . $sortOrder ."\");'>";
                     }else{
                         $thead .= "<td class='dbgrid_th' onclick='javascript:DBGrid.clickAjaxCol(\"". $col['sort'] ."\",\"ASC\");'>";
                     }
                     $thead .= "<span>" . $this->escape($col['label']) . "</span>" ;
                     $thead .= "</td>";
                 }
             }
             $thead .= "</tr></thead>";
        }
        return $thead;
    }
    
    protected function renderTableRows(){
        $columns = $this->_columns;
        $items = $this->paginator;
        $row = "";
        if(!empty($items) && !empty($columns)){
            $rowActionStatus = false;
            $rowActionMethod = "";
            $rowAction = "";
            $methodType = "";
            $row .= "<tbody>";
            foreach($items as $item){
                $row .= "<tr onmouseover='javascript:DBGrid.changeRowStyle(this,1)' onmouseout='javascript:DBGrid.changeRowStyle(this,0)'>";
                $row .= "<td class='dbgrid_td_ckb'><input type='checkbox' value='" . $item[$this->_primaryKey]  ."' name='dbgrid_item_ckb' /></td>";
                foreach($columns as $col){
                    $name = $col['name'];
                    $valueLabel = $col['valueLabel'];
                    if(!empty($col['action']) || $rowActionStatus){
                        $rowActionStatus = true;
                        if(empty($rowActionMethod)){
                            $rowActionMethod = $col['method'];
                        }
                        if(empty($rowAction)){
                            $rowAction = $col['action'];
                        }
                        if(empty($methodType)){
                            $methodType = $col['methodType'];
                        }
                        $editUrl = $this->_baseUrl . $this->_module . "/" . $rowAction . "/id/" . $item[$this->_primaryKey];
                        if($methodType == DBGridConstant::CALL_SELF_METHOD){
                            $row .= "<td class='dbgrid_td' style='cursor:pointer;' onclick='javascript:" . $rowActionMethod . "(\"$editUrl\")'>";
                        }else {
                            $row .= "<td class='dbgrid_td' ><a style='text-decoration:none;color:#000000;' href='$editUrl' >";
                        }
                    }else{
                        $row .= "<td class='dbgrid_td'>&nbsp;";
                    }
                    if(!empty($valueLabel)){
                        $valueLabelKey = $this->escape($item[$name]);
                        $row .= $this->escape($valueLabel[$valueLabelKey]);
                        
                    }else{
                        $row .= $this->escape($item[$name]);
                    }
                    if((!empty($col['action']) || $rowActionStatus) && $methodType != DBGridConstant::CALL_SELF_METHOD){
                        $row .= "&nbsp;</a></td>";
                    } else {
                    	 $row .= "&nbsp;</td>";
                    }
                }
                $row .= "</tr>";
            }
            $row .= "</tbody>";
        }
        return $row;
    }

    protected function renderAjaxTableRows(){
        $jsonDataArray = array();//json store
        $columns = $this->_columns;
        $items = $this->paginator;
        $row = "";
        if(!empty($items) && !empty($columns)){
            $rowActionStatus = false;
            $rowActionMethod = "";
            $rowAction = "";
            $methodType = "";
            $row .= "<tbody>";
            foreach($items as $item){
                $jsonData = array();//for json
                $row .= "<tr onmouseover='javascript:DBGrid.changeRowStyle(this,1)' onmouseout='javascript:DBGrid.changeRowStyle(this,0)'>";
                if($this->_returnData){
                    $row .= "<td class='dbgrid_td_ckb'><input type='checkbox' value='" . $item[$this->_primaryKey]  ."' name='dbgrid_item_ckb' /></td>";
                }
                foreach($columns as $col){
                    $name = $col['name'];
                    $valueLabel = $col['valueLabel'];
                    $visable = $col['visable'];
                    if($visable==true){
                        if(!empty($col['action']) || $rowActionStatus){
                            $rowActionStatus = true;
                            if(empty($rowActionMethod)){
                                $rowActionMethod = $col['method'];
                            }
                            if(empty($rowAction)){
                                $rowAction = $col['action'];
                            }
                            if(empty($methodType)){
                                $methodType = $col['methodType'];
                            }
                            $editUrl = $this->_baseUrl . $this->_module . "/" . $rowAction . "/id/" . $item[$this->_primaryKey];
                            if($methodType == DBGridConstant::CALL_SELF_METHOD){
                                $row .= "<td class='dbgrid_td' style='cursor:pointer;' onclick='javascript:" . $rowActionMethod . "(\"$editUrl\")'>";
                            }else {
                                $row .= "<td class='dbgrid_td' style='cursor:pointer;' onclick='javascript:DBGrid.gotoUrl(\"$editUrl\")'>";
                            }
                        }else{
                            $row .= "<td class='dbgrid_td'>&nbsp;";
                        }
                        if(!empty($valueLabel)){
                            $valueLabelKey = $this->escape($item[$name]);
                            $row .= $this->escape($valueLabel[$valueLabelKey]);
                        }else{
                            $row .= $this->escape($item[$name]);
                        }
                        $row .= "&nbsp;</td>";
                    }
                    if(!empty($valueLabel)){
                        $jsonData[$name] = $this->escape($valueLabel[$valueLabelKey]);//for json
                    }else{
                        $jsonData[$name] = $this->escape($item[$name]);//for json
                    }
                    $jsonDataArray[$item[$this->_primaryKey]] = $jsonData;
                }
                $row .= "</tr>";
            }
            $row .= "</tbody>";
        }

        if($this->_returnData){
            $json = json_encode($jsonDataArray);
            $row .= "<script type='text/javascript'>";
            $row .= "DBGrid.store = " . $json . ";";
            $row .= "</script>";
        }
        return $row;
    }

     /**
      * render pagination bar
      */
     protected function renderPaginationControl($pages,$showTitle = 0){
         $paginationBar = "";
         $select = "";
         $pageOptionValue = isset($this->_post['dbgridPageOption']) ? intval($this->_post['dbgridPageOption']) : DBGridConstant::DEFAULT_ITEM_COUNT_PER_PAGE;
         if(!empty($this->pageOptions)){
             $select .= "<select id='dbgridPageOptionSelect' style='height:21px;' onchange='javascript:DBGrid.changePageOption(this)'>";
             foreach($this->pageOptions as $key => $value){
                 if($pageOptionValue == $value){
                     $select .= "<option value='$key' selected>$value</option>";
                 }else{
                     $select .= "<option value='$key'>$value</option>";
                 }
             }
             $select .= "</select>";
         }
         $paginationBar .= "<div class='dbgrid_center_top'>";
         
         if(!empty($showTitle)){
             $pageLink = $this->_baseUrl . $this->_module;
             if(!empty($this->_pageTitleLink)){
                 $pageLink .= "/" . $this->_pageTitleLink;
             }
             //$paginationBar .= "<span class='dbgrid_center_top_title' onclick='javascript:Common.gotoUrl(\"$pageLink\");'>";
             $paginationBar .= "<span class='dbgrid_center_top_title' style='cursor:default;'>";
             $paginationBar .= $this->_pageTitle;
             $paginationBar .= "</span>";
             $paginationBar .= $this->renderModuleAction();
         }

         //for pages selection
         if($pages->pageCount){
         	 $pageIndex = 1;
         	 $select2 .= "<select id='dbgridPageOptionSelect2' style='height:21px;width:auto;' onchange='javascript:DBGrid.clickPageLink(this.value);'>";
         	 for($pageIndex;$pageIndex<$pages->pageCount+1;$pageIndex++){
         	     if($pageIndex == $pages->current){
                     $select2 .= "<option value='$pageIndex' selected>$pageIndex</option>";
                 }else{
                     $select2 .= "<option value='$pageIndex'>$pageIndex</option>";
                 }         	 	 
         	 }
         	 $select2 .= "</select>";
         }
         //

         if($pages->pageCount){
             
             $paginationBar .= "<div class='dbgrid_center_top_right'>";
             //page total
             $paginationBar .= "<div class='dbgrid_page_option'>". $pages->firstItemNumber ." 到 ". $pages->lastItemNumber . "  共" . $pages->totalItemCount . "项</div>";
             //page options
             $paginationBar .= "<div class='dbgrid_page_option'>$select</div>";
             $paginationBar .= "<div class='dbgrid_page_option'>$select2</div>";
             //first page link
             if(isset($pages->first)){
                $paginationBar .= "<div class='dbgrid_page_item' onclick='javascript:DBGrid.clickPageLink($pages->first);'><<</div>";
             }else{
                 $paginationBar .= "<div class='dbgrid_page_item'><<</div>";
             }
             //Previous page link
            if (isset($pages->previous)){
                $paginationBar .= "<div class='dbgrid_page_item' onclick='javascript:DBGrid.clickPageLink($pages->previous);'><</div>";
            }else{
                $paginationBar .= "<div class='dbgrid_page_item'><</div>";
            }
            //Numbered page links
            foreach ($pages->pagesInRange as $page){
                if ($page != $pages->current){
                    $paginationBar .= "<div class='dbgrid_page_item' onclick='javascript:DBGrid.clickPageLink($page);'>$page</div>";
                }else{
                     $paginationBar .= "<div class='dbgrid_page_item_current'>$page</div>";
                }
            }
            //Next page link
            if (isset($pages->next)){
                $paginationBar .= "<div class='dbgrid_page_item' onclick='javascript:DBGrid.clickPageLink($pages->next);'>></div>";
            }else{
                $paginationBar .= "<div class='dbgrid_page_item'>></div>";
            }
             //last page link
             if(isset($pages->last)){
                $paginationBar .= "<div class='dbgrid_page_item' onclick='javascript:DBGrid.clickPageLink($pages->last);'>>></div>";
             }else{
                 $paginationBar .= "<div class='dbgrid_page_item'>>></div>";
             }
            $paginationBar .= "</div>";

         }
         $paginationBar .= "</div>";
         return $paginationBar;
     }

     /**
      * for ajax
      */
     protected function renderAjaxPaginationControl($pages,$showTitle = 0){
         $paginationBar = "";
         $select = "";
         $pageOptionValue = isset($this->_post['dbgridPageOption']) ? intval($this->_post['dbgridPageOption']) : DBGridConstant::DEFAULT_ITEM_COUNT_PER_PAGE;
         if(!empty($this->pageOptions)){
             $select .= "<select id='dbgridPageOptionSelect' style='height:21px;' onchange='javascript:DBGrid.changeAjaxPageOption(this)'>";
             foreach($this->pageOptions as $key => $value){
                 if($pageOptionValue == $value){
                     $select .= "<option value='$key' selected>$value</option>";
                 }else{
                     $select .= "<option value='$key'>$value</option>";
                 }
             }
             $select .= "</select>";
         }
         $paginationBar .= "<div class='dbgrid_center_top'>";

         if(!empty($showTitle)){
             $paginationBar .= "<span class='dbgrid_center_top_title'>";
             $paginationBar .= $this->_pageTitle;
             $paginationBar .= "</span>";
             $paginationBar .= $this->renderModuleAction();
         }

         if($pages->pageCount){

             $paginationBar .= "<div class='dbgrid_center_top_right'>";
             //page total
             $paginationBar .= "<div class='dbgrid_page_option'>". $pages->firstItemNumber ." to ". $pages->lastItemNumber . " of " . $pages->totalItemCount . "</div>";
             //page options
             $paginationBar .= "<div class='dbgrid_page_option'>$select</div>";
             //first page link
             if(isset($pages->first)){
                $paginationBar .= "<div class='dbgrid_page_item' onclick='javascript:DBGrid.clickAjaxPageLink($pages->first);'><<</div>";
             }else{
                 $paginationBar .= "<div class='dbgrid_page_item'><<</div>";
             }
             //Previous page link
            if (isset($pages->previous)){
                $paginationBar .= "<div class='dbgrid_page_item' onclick='javascript:DBGrid.clickAjaxPageLink($pages->previous);'><</div>";
            }else{
                $paginationBar .= "<div class='dbgrid_page_item'><</div>";
            }
            //Numbered page links
            foreach ($pages->pagesInRange as $page){
                if ($page != $pages->current){
                    $paginationBar .= "<div class='dbgrid_page_item' onclick='javascript:DBGrid.clickAjaxPageLink($page);'>$page</div>";
                }else{
                     $paginationBar .= "<div class='dbgrid_page_item_current'>$page</div>";
                }
            }
            //Next page link
            if (isset($pages->next)){
                $paginationBar .= "<div class='dbgrid_page_item' onclick='javascript:DBGrid.clickAjaxPageLink($pages->next);'>></div>";
            }else{
                $paginationBar .= "<div class='dbgrid_page_item'>></div>";
            }
             //last page link
             if(isset($pages->last)){
                $paginationBar .= "<div class='dbgrid_page_item' onclick='javascript:DBGrid.clickAjaxPageLink($pages->last);'>>></div>";
             }else{
                 $paginationBar .= "<div class='dbgrid_page_item'>>></div>";
             }
            $paginationBar .= "</div>";

         }
         $paginationBar .= "</div>";
         return $paginationBar;
     }

     protected function renderModuleAction(){
         $moduleAction = "<div class='dbgrid_form_right'>";
         if(isset($this->_moduleActions)){
         foreach ($this->_moduleActions as $action) {
                $url = $this->_baseUrl . $this->_module . "/" . $action['action'];
                $param = "";
                if(!empty($action['params'])){
                    foreach($action['params'] as $key => $value){
                        $param .= $key . "/" . $value . "/";
                    }
                }
                if(!empty($param)){
                    $param = substr($param, 0 , sizeof($param) - 2);
                    $url = $url . "/" . $param;
                }
                switch(strtolower($action['name'])){
                    case "edit":
                        $moduleAction .= "<div class='dbgrid_form_btn_div' onclick='javascript:DBGrid.editBtn(\"$url\");'>";
                        $moduleAction .= "<div class='dbgrid_form_btn_pic'><img src='$this->_baseUrl/images/". strtolower($action['name']) .".gif'/></div><div class='dbgrid_form_btn_text'>". $action['label'] ."</div></div>";
                        break;
                    case "delete":
                        $moduleAction .= "<div class='dbgrid_form_btn_div' onclick='javascript:DBGrid.deleteBtn(\"$url\");'>";
                        $moduleAction .= "<div class='dbgrid_form_btn_pic'><img src='$this->_baseUrl/images/". strtolower($action['name']) .".gif'/></div><div class='dbgrid_form_btn_text'>". $action['label'] ."</div></div>";
                        break;
                    case "add":
                        if($action["methodType"] == DBGridConstant::CALL_SELF_METHOD ){
                            $moduleAction .= "<div class='dbgrid_form_btn_div' onclick='javascript:" . $action["method"] . "(\"$url\");'>";
                        }else{
                            $moduleAction .= "<div class='dbgrid_form_btn_div' >";
                        }
                        $moduleAction .= "<a style='text-decoration:none;color:#005A5A;' href='$url' ><div class='dbgrid_form_btn_pic'><img style='border:0px;' src='$this->_baseUrl/images/". strtolower($action['name']) .".gif'/></div><div class='dbgrid_form_btn_text'>". $action['label'] ."</div></a></div>";
                        break;
                    default :
                        $moduleAction .= "<div class='dbgrid_form_btn_div' onclick='javascript:". $action['action'] ."();'>";
                        $moduleAction .= "<div class='dbgrid_form_btn_pic'><img src='$this->_baseUrl/images/". strtolower($action['name']) .".gif'/></div><div class='dbgrid_form_btn_text'>". $action['label'] ."</div></div>";
                        break;
                }
            }
         }
         if($this->_isExport){
               $moduleAction .= "<div class='dbgrid_form_btn_div' onclick='javascript:DBGrid.exportData();'><div class='dbgrid_form_btn_pic'><img src='$this->_baseUrl/images/export.gif'/></div><div class='dbgrid_form_btn_text'>" . $this->_translate->translate("exportBtn") . "</div></div>";
         }
         //for return data
         if($this->_returnData){
               $moduleAction .= "<div class='dbgrid_form_btn_div' onclick='javascript:DBGrid.returnData($this->_callBackMethod);'><div class='dbgrid_form_btn_pic'><img src='$this->_baseUrl/images/return_s.gif'/></div><div class='dbgrid_form_btn_text'>" . $this->_translate->translate("returnBtn") . "</div></div>";
         }

         $moduleAction .= "</div>";

         return $moduleAction;
     }
}
